<template>
    <div>
        <div>
            <el-form ref="searchForm" :inline="true" :model="condition.search" label-suffix="" label-width="100px"
                     label-position="left" size="small">
                <el-row>
                    <el-col :span=6>
                        <el-form-item label="门店" prop="shopId">
                            <el-select v-model="condition.search.shopId" placeholder="请选择门店" style="width:200px;">
                                <el-option
                                    v-for="item in shops"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id">
                                    {{ item.name }}
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span=6 v-if="!mobileNo">
                        <el-form-item label="手机号" prop="mobileNo">
                            <el-input v-model="condition.search.mobileNo" placeholder="手机号"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span=6>
                        <el-form-item label="预定来源" prop="reserveSource">
                            <el-select v-model="condition.search.reserveSource" placeholder="预定来源">
                                <el-option label="大众点评" value="大众点评"></el-option>
                                <el-option label="内定" value="内定"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span=6>
                        <el-form-item label="预定日期" prop="reserveDate">
                            <el-date-picker
                                v-model="condition.search.reserveDate"
                                type="date"
                                placeholder="预定日期"
                                value-format="yyyy-MM-dd"
                                align="right">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <el-form-item>
                            <el-button type="primary" @click="getData">查询</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="showAddDialog">新增</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="reset">重置</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="exportExcel">导出</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="success" @click="download">下载预定模版</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="success" @click="upload">上传</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <el-table
            id="mainTable"
            size="small"
            :data="tableData"
            v-loading="loading"
            element-loading-text="拼命加载中"
            element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(0, 0, 0, 0.8)"
            header-cell-class-name="tableHeaderStyle"
            :row-class-name="tableRowClassName">
            <el-table-column label="序号" width="50">
                <template v-slot="scope">
                    <span>{{ (condition.page - 1) * condition.rows + scope.$index + 1 }}</span>
                </template>
            </el-table-column>
            <el-table-column
                prop="mobileNo"
                width="100px"
                label="手机号">
            </el-table-column>
            <el-table-column
                prop="shopName"
                width="100px"
                label="门店">
            </el-table-column>
            <el-table-column
                prop="nickname"
                width="80px"
                label="称呼">
            </el-table-column>
            <el-table-column
                prop="level"
                width="80px"
                label="等级">
                <template v-slot="scope">
                    <el-tag type="success" effect="dark" size="small"
                            v-if="scope.row.level == 'CORE' || scope.row.level == '核心'">
                        {{ formatLevel(scope.row, scope.column, scope.row.level) }}
                    </el-tag>
                    <el-tag type="" effect="dark" size="small"
                            v-if="scope.row.level == 'IMPORTANT' || scope.row.level == '重要'">
                        {{ formatLevel(scope.row, scope.column, scope.row.level) }}
                    </el-tag>
                    <el-tag type="info" size="small" effect="dark"
                            v-if="scope.row.level == 'GENERAL' || scope.row.level == '一般'">
                        {{ formatLevel(scope.row, scope.column, scope.row.level) }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column
                prop="age"
                width="80px"
                :formatter="formatAge"
                label="年龄">
            </el-table-column>
            <el-table-column
                prop="gender"
                width="80px"
                :formatter="formatGender"
                label="性别">
            </el-table-column>
            <el-table-column
                prop="reserveDate"
                width="100px"
                label="预定日期">
            </el-table-column>
            <el-table-column
                prop="reserveTime"
                width="80px"
                label="用餐时间">
            </el-table-column>
            <el-table-column
                prop="reserveNum"
                width="80px"
                label="预定人数">
            </el-table-column>
            <el-table-column
                prop="reserveSit"
                width="80px"
                label="座位类型">
            </el-table-column>
            <el-table-column
                prop="reserveSource"
                width="80px"
                label="预定来源">
            </el-table-column>
            <el-table-column
                prop="reserveTimes"
                width="80px"
                label="预定次数">
            </el-table-column>
            <el-table-column
                prop="label"
                label="预定标签">
            </el-table-column>
            <el-table-column
                prop="flavour"
                label="顾客口味">
            </el-table-column>
            <el-table-column
                prop="updateTime"
                label="更新时间">
            </el-table-column>
            <el-table-column
                v-if="!mobileNo"
                label="操作"
                fixed="right"
                align="center"
                width="120px">
                <template v-slot="scope">
                    <div>
                        <el-button @click="onDetail(scope.row)" type="text" size="small">详情</el-button>
                        <el-button @click="showUpdateDialog(scope.row)" type="text" size="small">编辑</el-button>
                        <el-button @click="onDelete(scope.row)" type="text" size="small">删除</el-button>
                    </div>
                </template>
            </el-table-column>
            <el-table-column
                v-if="mobileNo"
                label="操作"
                fixed="right"
                align="center"
                width="80px">
                <template v-slot="scope">
                    <div>
                        <el-button @click="showUpdateDialog(scope.row)" type="text" size="small">编辑</el-button>
                        <el-button @click="onDelete(scope.row)" type="text" size="small">删除</el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            background
            small
            :hide-on-single-page="true"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="condition.page"
            :page-sizes="[10, 20, 30, 40, 50, 100]"
            :page-size.sync="condition.rows"
            layout="sizes, prev, pager, next"
            :total.sync="condition.total">
        </el-pagination>
        <el-drawer ref="drawer" direction="rtl" :title=addOrUpdateDialogTitle width="30%"
                   :visible.sync="addOrUpdateDialogVisible">
            <el-form :model="addOrUpdateForm" label-width="120px" size="small">
                <el-form-item label="选择门店">
                    <el-select v-model="addOrUpdateForm.shopId" placeholder="请选择门店" style="width:200px;">
                        <el-option
                            v-for="item in shops"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                            {{ item.name }}
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="手机号">
                    <el-input v-model="addOrUpdateForm.mobileNo" placeholder="手机号" @blur="mobileNoBlur"></el-input>
                </el-form-item>
                <el-form-item label="预定日期">
                    <el-date-picker
                        v-model="addOrUpdateForm.reserveDate"
                        type="date"
                        placeholder="预定日期"
                        value-format="yyyy-MM-dd"
                        align="right">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="用餐时间">
                    <el-select v-model="addOrUpdateForm.reserveTime" placeholder="用餐时间">
                        <el-option label="晚餐" value="晚餐"></el-option>
                        <el-option label="午餐" value="午餐"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="称呼">
                    <el-input v-model="addOrUpdateForm.nickname" placeholder="称呼"></el-input>
                </el-form-item>
                <el-form-item label="人数">
                    <el-input v-model="addOrUpdateForm.reserveNum" placeholder="预定人数"
                              oninput="value=value.replace(/[^\d]/g,'')"></el-input>
                </el-form-item>
                <el-form-item label="座位">
                    <el-select v-model="addOrUpdateForm.reserveSit" placeholder="预定座位类型">
                        <el-option label="包厢" value="包厢"></el-option>
                        <el-option label="大堂" value="大堂"></el-option>
                        <el-option label="板前" value="板前"></el-option>
                        <el-option label="吧台" value="吧台"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="来源">
                    <el-select v-model="addOrUpdateForm.reserveSource" placeholder="预定来源">
                        <el-option label="大众点评" value="大众点评"></el-option>
                        <el-option label="内定" value="内定"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="年龄">
                    <el-select v-model="addOrUpdateForm.age" placeholder="年龄">
                        <el-option
                            v-for="item in ageOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="级别">
                    <el-select v-model="addOrUpdateForm.level" placeholder="级别">
                        <el-option
                            v-for="item in levelOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="性别">
                    <el-select v-model="addOrUpdateForm.gender" placeholder="性别">
                        <el-option
                            v-for="item in genderOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="预定标签">
                    <el-input v-model="addOrUpdateForm.label" placeholder="预定标签，比如老人过生日，生日聚会等"
                              type="textarea"></el-input>
                </el-form-item>
                <el-form-item label="个人口味">
                    <el-input v-model="addOrUpdateForm.flavour" placeholder="个人口味，比如不喜欢吃辣，不喜欢葱蒜"
                              type="textarea"></el-input>
                </el-form-item>
            </el-form>
            <div class="drawer-footer">
                <el-button class="drawer-footer-button" @click="addOrUpdateDialogVisible = false" size="small">取 消
                </el-button>
                <el-button class="drawer-footer-button" @click="addOrUpdateConfirm" type="primary" size="small">确 定
                </el-button>
            </div>
        </el-drawer>

        <el-dialog title="上传预定文件" width="30%" :visible.sync="uploadDialogVisible">
            <el-form :model="uploadDialogForm" label-width="120px">
                <el-form-item label="请选择文件">
                    <el-upload
                        ref="upload"
                        :action="uploadReserveTemplate()"
                        :headers="uploadHeaders()"
                        :multiple="false"
                        :limit="1"
                        accept=".xlsx"
                        :auto-upload="false"
                        :show-file-list="true"
                        :file-list="fileList"
                        :on-success="handleSuccess">
                        <el-button size="mini" type="success">点击上传</el-button>
                        <div slot="tip" class="el-upload__tip">
                            <div class="upload-tips">只能上传Exel文件，每次只能上传一个，如果有多个请分开上传</div>
                        </div>
                    </el-upload>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" @click="uploadDialogVisible = false">取 消</el-button>
                <el-button size="small" @click="uploadConfirm" type="primary" v-loading.fullscreen.lock="uploadLoading">
                    确 定
                </el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    addReserve,
    deleteReserve,
    getReserveByPage,
    getReserveDownloadUrl,
    getReserveUploadUrl,
    getShopByPage,
    selectCustomerByMobileNo,
    updateReserve
} from '@/api/api'
import db from '@/utils/localstorage'
import {Message} from "element-ui";

export default {
    name: "Reserve",
    data() {
        return {
            // 分页搜索条件
            condition: {
                page: 1,
                rows: 10,
                total: 0,
                search: {}
            },
            loading: true,
            // 表格数据
            tableData: [],
            // 新增或者编辑对话框显示
            addOrUpdateDialogVisible: false,
            // 标题
            addOrUpdateDialogTitle: '新增',
            // 新增或者编辑对话框表单
            addOrUpdateForm: {},
            // 选中行
            selectedRow: {},
            // 门店数据
            shops: [],

            // 上传对话框
            uploadDialogVisible: false,
            fileList: [],
            uploadDialogForm: {},
            // 上传loading
            uploadLoading: false,

            ageOptions: this.CONST.age_options,
            levelOptions: this.CONST.level_options,
            positionOptions: this.CONST.position_options,
            genderOptions: this.CONST.gender_options,
        }
    },
    // 这里定义需要父组件传过来的东西
    props: {
        size: {
            type: String,
            default: 'small'
        },
        mobileNo: String,
        shopId: String,
    },
    methods: {
        // 这里可以单独设置每一行的样式
        tableRowClassName({row, rowIndex}) {
            return '';
        },
        handleSuccess(response, file, fileList) {
            this.uploadLoading = false;
            this.fileList = [];
            if (response.respCode != 1000) {
                Message.error('异常码：' + response.respCode + '，异常信息：' + response.respMsg);
            } else {
                this.$message({
                    type: 'success',
                    duration: 6000,
                    message: '上传成功！\n' +
                        '导入成功: ' + response.body.successCount + '条！\n' +
                        '导入失败: ' + response.body.failCount + '条！\n' +
                        '失败原因: ' + response.body.failReason + '\n'
                });
                this.getData();
                this.uploadDialogVisible = false;
            }
        },
        uploadHeaders() {
            return {'token': db.getUser().token};
        },
        uploadReserveTemplate() {
            return getReserveUploadUrl();
        },
        upload: function () {
            this.uploadDialogVisible = true;
        },
        uploadConfirm: function () {
            let files = this.$refs.upload.uploadFiles
            if (files.length == 0) {
                this.$message({
                    type: 'error',
                    message: '请先选择文件!'
                });
            } else {
                this.uploadLoading = true;
                this.$refs.upload.submit();
            }
        },
        handleSizeChange(val) {
            this.getData();
        },
        handleCurrentChange(val) {
            this.getData();
        },
        mobileNoBlur(e) {
            let value = e.target.value;
            if (value && value.length === 11) {
                selectCustomerByMobileNo({'mobileNo': value}).then(data => {
                    if (data.body) {
                        this.$set(this.addOrUpdateForm, "nickname", data.body.nickname)
                        this.$set(this.addOrUpdateForm, "flavour", data.body.flavour)
                    }
                })
            } else {
            }
        },
        // 格式布尔值
        formatBoolean: function (row, column, cellValue) {
            if (cellValue) {
                return "是";
            } else {
                return "否";
            }
        },
        formatReserveTime: function (row, column, cellValue) {
            if (!cellValue) {
                return;
            }
            if (cellValue == '晚餐') {
                return "晚餐";
            } else if (cellValue == '午餐') {
                return "午餐";
            } else {
                return "未知";
            }
        },
        formatAge: function (row, column, cellValue) {
            if (!cellValue) {
                return;
            }
            for (const elem of this.ageOptions) {
                if (elem.value == cellValue) {
                    return elem.label;
                }
            }
            return "未知";
        },
        formatLevel: function (row, column, cellValue) {
            if (!cellValue) {
                return;
            }
            for (const elem of this.levelOptions) {
                if (elem.value == cellValue) {
                    return elem.label;
                }
            }
            return "未知";
        },
        formatPosition: function (row, column, cellValue) {
            if (!cellValue) {
                return;
            }
            for (const elem of this.positionOptions) {
                if (elem.value == cellValue) {
                    return elem.label;
                }
            }
            return "未知";
        },
        formatGender: function (row, column, cellValue) {
            if (!cellValue) {
                return;
            }
            for (const elem of this.genderOptions) {
                if (elem.value == cellValue) {
                    return elem.label;
                }
            }
            return "未知";
        },
        getCurrentDate() {
            let d = new Date(),
                month = '' + (d.getMonth() + 1),
                day = '' + d.getDate(),
                year = d.getFullYear()
            if (month.length < 2) month = '0' + month;
            if (day.length < 2) day = '0' + day;
            return [year, month, day].join('-');
        },
        showAddDialog: function () {
            this.addOrUpdateDialogTitle = '新增';
            this.addOrUpdateDialogVisible = true;
            // this.addOrUpdateForm = {'reserveDate': this.getCurrentDate(), 'labels': []};
            this.addOrUpdateForm = {'reserveDate': this.getCurrentDate()};
        },
        showUpdateDialog: function (row) {
            this.addOrUpdateDialogTitle = '编辑';
            this.addOrUpdateDialogVisible = true;
            this.selectedRow = row;
            // 深拷贝
            this.addOrUpdateForm = Object.assign({}, row);
            // if (this.addOrUpdateForm.label) {
            //     this.$set(this.addOrUpdateForm, "labels", this.addOrUpdateForm.label.split(','))
            // } else {
            //     this.$set(this.addOrUpdateForm, "labels", [])
            // }
        },
        reset: function () {
            this.$refs['searchForm'].resetFields();
        },
        exportExcel: function () {
            this.GLOBAL.exportExcel('#mainTable', '数据.xlsx');
        },
        download: function () {
            window.open(getReserveDownloadUrl() + "?token=" + db.getUser().token, '_blank');
        },
        add: function () {
            console.log(this.addOrUpdateForm);
            // this.addOrUpdateForm.label = this.addOrUpdateForm.labels.join(',');
            addReserve(this.addOrUpdateForm).then(data => {
                if (data.respCode == 1000) {
                    this.addOrUpdateDialogVisible = false;
                    this.getData();
                }
            });
        },
        update: function () {
            // this.addOrUpdateForm.label = this.addOrUpdateForm.labels.join(',');
            updateReserve(this.addOrUpdateForm).then(data => {
                if (data.respCode == 1000) {
                    this.addOrUpdateDialogVisible = false;
                    this.getData();
                }
            });
        },
        onDetail: function (row) {
            this.$router.push({path: '/customer/detail', query: {mobileNo: row.mobileNo}});
        },
        onDelete: function (row) {
            this.$confirm('请确认是否删除, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteReserve({id: row.id}).then(data => {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.getData();
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        addOrUpdateConfirm: function () {
            if (this.addOrUpdateDialogTitle == '新增') {
                this.add();
            } else if (this.addOrUpdateDialogTitle == '编辑') {
                this.update();
            }
        },
        // 获取门店列表
        getShops: function () {
            let condition = {
                page: 1,
                rows: 100,
                search: {}
            };
            getShopByPage(condition).then(data => {
                this.shops = data.body.rows;
            });
        },
        // 获取表格数据
        getData: function () {
            if (this.mobileNo) {
                this.condition.search.mobileNo = this.mobileNo;
            }
            if (this.shopId) {
                this.condition.search.shopId = this.shopId;
            }
            getReserveByPage(this.condition).then(data => {
                this.tableData = data.body.rows;
                this.condition.total = data.body.total;
                this.loading = false;
            });
        },
    },
    created() {
        this.getData();
        this.getShops();
    },
}
</script>

<style scoped>
.el-input {
    width: 150px !important;
}

.el-select {
    width: 150px !important;
}
</style>
